package com.googlecode.intellimars.sabotter;

import com.googlecode.intellimars.sabotter.ui.SabotterWindow;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.peer.PeerFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.util.xmlb.XmlSerializerUtil;
import org.jetbrains.annotations.NotNull;

// SabotterPluginからIntelliJのまじないっぽいところを抽出
public abstract class SabotterProjectComponent implements ProjectComponent, PersistentStateComponent<SabotterConfig> {
    public static final String TOOL_WINDOW_ID = "Sabotter";
    
    public SabotterConfig config;
    public Project project;
    protected SabotterWindow sabotterWindow;

    public SabotterProjectComponent(Project project) {
        this.project = project;
        this.config = new SabotterConfig();
    }

    public void initComponent() { }
    public void disposeComponent() { }

    public void projectOpened() {
        sabotterWindow.setData(config);
        ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
        ToolWindow toolWindow = toolWindowManager.registerToolWindow(TOOL_WINDOW_ID, false, ToolWindowAnchor.RIGHT);
        ContentFactory contentFactory = PeerFactory.getInstance().getContentFactory();
        Content content = contentFactory.createContent(sabotterWindow.rootPanel, "", false);
        toolWindow.getContentManager().addContent(content);
    }

    public void projectClosed() {
        ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
        toolWindowManager.unregisterToolWindow(TOOL_WINDOW_ID);
     }

    public SabotterConfig getState() {
        return config;
    }

    public void loadState(SabotterConfig state) {
        XmlSerializerUtil.copyBean(state, config);
    }

    @NotNull
    public String getComponentName() {
        return "SabotterPlugin";
    }
}
